<template>
  <div class="columns">
    <div class="cols-left">
      <div v-for="(x, y) in tables" @click="selectTable(y)" :class="y == tableIdx ? 'active' : ''">
        {{ x }}
      </div>
    </div>
    <div class="cols-right">
      <!-- <div class="btn">
        <el-button type="primary" @click="handleAdd">添加</el-button>
      </div> -->
      <el-tabs v-model="activeName" @tab-click="handleClick" type="border-card">
        <el-tab-pane label="字段" name="0">
          <div class="table">
            <el-table :data="fieldData" border style="width: 100%">
              <el-table-column type="index" width="60" label="顺序" align="center" />
              <template v-for="(x, y) in fieldColumns" :key="y">
                <el-table-column :prop="x.name" :label="x.title" :width="x.width" align="center" />
              </template>
              <el-table-column prop="action" label="操作" width="230" align="center">
                <template #default="scope">
                  <el-button @click="handleAdd(scope.row)">添加</el-button>
                  <!-- <el-button @click="handleEdit(scope.row)">编辑</el-button>
                  <el-button type="danger">删除</el-button> -->
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        <el-tab-pane label="参数" name="1">
          <div class="btn">
            <el-button type="primary" @click="handleAdd">添加</el-button>
            <el-button type="primary" @click="handleAll" v-if="columnData.length == 0">一键添加</el-button>
          </div>
          <div class="table" style="margin: 10px 0;">
            <el-table :data="columnData" border style="width: 100%">
              <el-table-column type="index" width="60" label="顺序" align="center" />
              <template v-for="(x, y) in baseColumns" :key="y">
                <el-table-column :prop="x.name" :label="x.title" :width="x.width" align="center" />
              </template>
              <el-table-column prop="createTime" label="创建时间" width="180" align="center">
                <template #default="scope">
                  {{ global.formatDataTime(scope.row.creatTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="action" label="操作" width="230" align="center">
                <template #default="scope">
                  <el-button>查看</el-button>
                  <el-button @click="handleEdit(scope.row)">编辑</el-button>
                  <el-button type="danger">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        <el-tab-pane label="数据" name="2">
          <div class="table">
            <el-table :data="tableData" border style="width: 100%">
              <el-table-column type="index" width="60" label="顺序" align="center" />
              <template v-for="(x, y) in searchColumns" :key="y">
                <el-table-column :prop="x.name" :label="x.title" :width="x.width" align="center" />
              </template>
              <el-table-column prop="createTime" label="创建时间" width="180" align="center">
                <template #default="scope">
                  {{ global.formatDataTime(scope.row.creatTime) }}
                </template>
              </el-table-column>
              <!-- <el-table-column prop="action" label="操作" width="230" align="center">
                <template #default="scope">
                  <el-button>查看</el-button>
                  <el-button @click="handleEdit(scope.row)">编辑</el-button>
                  <el-button type="danger">删除</el-button>
                </template>
              </el-table-column> -->
            </el-table>

          </div>
        </el-tab-pane>
      </el-tabs>

      <div class="dialog">
        <el-dialog :title="title" v-model="open" width="800px">
          <el-form ref="formRef" :model="form" size="default" label-width="150px">
            <el-form-item v-for="(x, y) in baseColumns" :key="y" :label="x.title" :prop="x.name">
              <el-input v-model="form[x.name]" :placeholder="'请输入' + x.title" @keyup.enter="submit" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer" style="display: flex;justify-content: right;">
            <div>
              <el-button type="primary" @click="submit">保 存</el-button>
              <el-button @click="() => { open = false }">取 消</el-button>
            </div>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script setup>
import { baseApi } from '@/apis/base';
import { onMounted, ref } from 'vue';
import { global } from '@/utils/global';
import { get, post } from '@/utils/request'
import element from '@/utils/element';
const tables = ref([])
const columnData = ref([])
const fieldData = ref([])
const tableData = ref([])
const form = ref(null)
const open = ref(false)
const title = ref('')
const tableIdx = ref(0)
const option = {
  name: 'columns',
  title: '参数'
}
const activeName = ref('0')
const tname = ref('columns')
const searchColumns = ref([])
const baseColumns = ref([])
const fieldColumns = ref([
  {
    title: '字段',
    name: 'Field',
    width: 110
  },
  {
    title: '类型',
    name: 'Type',
    width: 110
  },
  {
    title: '允许为空',
    name: 'Defalut',
    width: 100
  },
  {
    title: '默认',
    name: 'Null',
    width: 80
  },
  {
    title: '说明',
    name: 'Key',
    width: 180
  },
  {
    title: '注释',
    name: 'comment',
    width: 180
  },
  // {
  //   title: '自增',
  //   name: 'Extra'
  // },
  // {
  //   title: '说明',
  //   name: 'comment'
  // }
])
function resetForm() {
  let obj = {}
  searchColumns.value.map(x => {
    obj[x] = ''
  })
  form.value = obj
}

function handleAdd(row) {
  title.value = `添加${option.title}`
  resetForm()
  open.value = true
  form.value.tname = tname.value
  form.value.width = 120
  if (row) {
    console.log(row.Field)
    form.value.name = row.Field
  }
  console.log(fieldData.value)
}

function handleAll(){
  fieldData.value.map(x=>{

  })
}

function handleEdit(row) {
  title.value = `编辑${option.title}`
  open.value = true
  form.value = row
  console.log(form.value)
}

function submit() {
  const params = {}
  baseColumns.value.map(x => {
    params[x.name] = form.value[x.name]
  })
  // params.tname = tname.value
  if (form.value.id) {
    params.id = form.value.id
    editFn(params)
  } else {
    addFn(params)
  }
}

function moveItemToTop(arr, item) {
  const index = arr.indexOf(item);
  if (index > -1) {
    arr.splice(index, 1); // 移除该项
    arr.unshift(item); // 将该项添加到数组开始位置
  }
}

function editFn(data) {
  post(`/base/edit`, data).then(res => {
    if (res.code == 200) {
      successFn('编辑')
    } else {
      failFn(res)
    }
  })
}

function addFn(data) {
  post(`/base/add`, data).then(res => {
    if (res.code == 200) {
      successFn('添加')
    } else {
      failFn(res)
    }
  })
}

function successFn(str) {
  handleSearch()
  open.value = false
  element.success(str + '成功')
}

function allTables() {
  baseApi.allTables().then(res => {
    tables.value = res.data
    moveItemToTop(tables.value, 'columns')
    getBaseColumns('columns')
    tableInfo()
  })
}

function handleSearch() {
  getColumns()
  tableInfo()
  getList()
}

function getColumns() {
  baseApi.columnsList({
    tname: tname.value
  }).then(res2 => {
    columnData.value = res2.data
    searchColumns.value = res2.data
  })
}

function getBaseColumns(tname) {
  baseApi.columnsList({ tname }).then(res => {
    baseColumns.value = res.data
  })
}

function getList() {
  get(`${tname.value}/list`).then(res => {
    tableData.value = res.data
  })
}

function handleClick(e) {
  activeName.value = e.index
  switch (e.index) {
    case '1':
      getColumns()
      break;
    case '2':
      getList()
      break;
  }
}

function toggleObj(str) {
  let obj = {}
  fieldColumns.value.map((a, b) => {
    // console.log(str.split(' ').slice(2)[b])
    if (str.split(' ').slice(2)[b]) {
      obj[a.name] = str.split(' ').slice(2)[b].replace(/,/g, '').replace(/`/g, '').replace(/\'/g, '')
    }
  })
  return obj
}

function tableInfo() {
  baseApi.tableInfo({
    tname: tname.value,
  }).then(res => {
    fieldData.value = res.data
    const arr = []
    const list = res.data[0]['Create Table'].split('\n').slice(0, -2)
    const list2 = list.slice(1)
    list2.map(x => {
      arr.push(toggleObj(x))
    })
    fieldData.value = arr
  })
}

function selectTable(y) {
  tableIdx.value = y
  activeName.value = '0'
  tname.value = tables.value[y]
  tableInfo()
}

onMounted(() => {
  allTables()
})
</script>
<style scoped lang="scss">
.columns {
  display: flex;

  .cols-left {
    background-color: #fff;
    padding: 10px 20px;
    margin-right: 10px;
    border: 1px solid #ddd;

    >div {
      cursor: pointer;
    }

    .active {
      color: red;
    }
  }

  .cols-right {
    >div {
      margin-bottom: 10px;
    }
  }
}
</style>
